﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ZK.YHP_TransManage.Test
{
    public class tt
    {
        public string gMac { get; set; }
        public List<ttt> recv { get; set; }
    }

    public class ttt
    {
        public string mac { get; set; }
        public string data { get; set; }
    }

    public partial class 蓝牙天线启动监听服务 : Form
    {
        public 蓝牙天线启动监听服务()
        {
            InitializeComponent();
            t1();
        }

        void t1()
        {
            var q1 = "{ \"gMac\":\"d81105000101\",\"recv\":[{ \"mac\":\"b001000021d9\",\"data\":\"f33fffff090100c4303031343933313934303835\"}]}";
            var q2 = " { \"gMac\":\"d81105000101\",\"recv\":[{ \"mac\":\"b001000021d9\",\"data\":\"3133383637320000000000000000000000000000\"},{ \"mac\":\"b001000021d9\",\"data\":\"00c9c24131323735340000bbfab7e22843444c53\"},{ \"mac\":\"b001000021d9\",\"data\":\"3400000000000000000000486502000012330200\"},{ \"mac\":\"b001000021d9\",\"data\":\"0000000000000000000000000000000000000034\"}]}";
            var q3 = "{ \"gMac\":\"d81105000101\",\"recv\":[{ \"mac\":\"b001000021d9\",\"data\":\"3100000000000000000000000000000000000000\"},{ \"mac\":\"b001000021d9\",\"data\":\"0000000000000000000000000000000000000000\"},{ \"mac\":\"b001000021d9\",\"data\":\"0000000000000000000000000000000000000000\"},{ \"mac\":\"b001000021d9\",\"data\":\"0000000000000000000000000000000000000000\"}]}";
            var q4 = "{ \"gMac\":\"d81105000101\",\"recv\":[{ \"mac\":\"b001000021d9\",\"data\":\"0000000000000000000000000000000023232323\"},{ \"mac\":\"b001000021d9\",\"data\":\"232331325ef44f\"}]}";
            List<string> vs = new List<string>();
            vs.Add(q1);
            vs.Add(q2);
            vs.Add(q3);
            vs.Add(q4);
            string data = string.Empty;
            foreach (var item in vs)
            {
                var ss = Newtonsoft.Json.JsonConvert.DeserializeObject<tt>(item);
                foreach (var j in ss.recv)
                {
                    data += j.data;
                }
            }
            Console.WriteLine(data);
        }

        static int status1 = 6;

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                //点击开始监听时 在服务端创建一个负责监听IP和端口号的Socket
                Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Any;
                //创建对象端口
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(textBoxPort.Text));

                socketWatch.Bind(point);//绑定端口号
                ShowMsg("监听成功!");
                socketWatch.Listen(10);//设置监听

                //创建监听线程
                Thread thread = new Thread(Listen);
                thread.IsBackground = true;
                thread.Start(socketWatch);
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
            }
        }

        Dictionary<string, Socket> socketList = new Dictionary<string, Socket>();

        /// <summary>
        /// 等待客户端的连接 并且创建与之通信的Socket
        /// </summary>
        Socket socketSend;
        void Listen(object o)
        {
            try
            {
                Socket socketWatch = o as Socket;
                while (true)
                {

                    socketSend = socketWatch.Accept();//等待接收客户端连接
                    ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功!");

                    socketList.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
                    this.Invoke(new Action(() =>
                    {
                        this.comboBoxIps.Items.Add(socketSend.RemoteEndPoint.ToString());
                    }));

                    //开启一个新线程，执行接收消息方法
                    Thread r_thread = new Thread(Received);
                    r_thread.IsBackground = true;
                    r_thread.Start(socketSend);
                }
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
            }
        }

        /// <summary>
        /// 服务器端不停的接收客户端发来的消息
        /// </summary>
        /// <param name="o"></param>
        void Received(object o)
        {
            try
            {
                Socket socketSend = o as Socket;
                while (true)
                {
                    //客户端连接服务器成功后，服务器接收客户端发送的消息
                    byte[] buffer = new byte[1024 * 1024 * 3];
                    //实际接收到的有效字节数
                    int len = socketSend.Receive(buffer);
                    if (len == 0)
                    {
                        break;
                    }
                    string str = Encoding.UTF8.GetString(buffer, 0, len);
                    if (str.Contains("\"opt\":1,\"resp\":\"ok\"")) { Common.Log4.LogManage.WriteWarn("开始连接返回 " + str); status1 = 1; }
                    if (str.Contains("\"opt\":4,\"resp\":\"ok\"")) { Common.Log4.LogManage.WriteWarn("开始断开返回 " + str); status1 = 5; }
                    if (str.Contains("\"opt\":3,\"resp\":\"ok\"")) { Common.Log4.LogManage.WriteWarn("开始发送返回 " + str); status1 = 3; }
                    if (str.Contains("\"connresp\":\"connected\"")) { Common.Log4.LogManage.WriteWarn("已连接 " + str); status1 = 2; }
                    if (str.Contains("\"connresp\":\"disconnected\"")) { Common.Log4.LogManage.WriteWarn("已断开 " + str); status1 = 6; }
                    //if (str.Contains("recv")) { Common.Log4.LogManage.WriteWarn("已读取 " + str); status1 = 4; }
                    if (str.Contains("000000023232323") || str.Contains("f33fff")) { Common.Log4.LogManage.WriteWarn("已读取 " + str); status1 = 4; }

                    ShowMsg(socketSend.RemoteEndPoint + ":" + str);
                }
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
            }
        }
        /// <summary>
        /// 服务器向客户端发送消息
        /// </summary>
        /// <param name="str"></param>
        void Send(string str)
        {
            if (str.Contains("{"))
            {
                Common.Log4.LogManage.WriteWarn("send " + str);
            }
            ShowMsg(str);
            byte[] buffer = Encoding.UTF8.GetBytes(str);
            socketSend.Send(buffer);
        }
        void ShowMsg(string msg)
        {
            Common.Log4.LogManage.WriteInfo("显示 " + msg);

            this.Invoke(new Action(() =>
            {
                if (textBox1.Text.Length > 30000) textBox1.Text = textBox1.Text.Substring(0, 20000);
                textBox1.AppendText(DateTime.Now.ToString("HH:mm:ss") + "--" + msg + "\r\n");
            }));
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Send(textBoxMsg.Text.Trim());
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    Thread.Sleep(100);
                    //连接
                    while (true)
                    {
                        Thread.Sleep(100);
                        if (status1 == 6)
                        {
                            break;
                        }
                    }
                    //Send("{\"gMac\":\"d81105000101\", \"msgid\":1, \"opt\":1, \"mac\":[\"dff48f18f5bc\"]}");
                    Send("{\"gMac\":\"d81105000101\", \"msgid\":1, \"opt\":1, \"mac\":[\"b001000021d9\"]}");
                    //读取
                    while (true)
                    {
                        Thread.Sleep(100);
                        if (status1 == 2)
                        {
                            break;
                        }
                    }
                    //Send("{\"gMac\":\"d81105000101\",\"msgid\":1,\"opt\":3,\"mac\":\"dff48f18f5bc\",\"data\":\"F201020304000000002F\"}");
                    Send("{\"gMac\":\"d81105000101\",\"msgid\":1,\"opt\":3,\"mac\":\"b001000021d9\",\"data\":\"F11FFFFF09010011310000000000000000313233343132333422F22F\"}");
                    // 断开
                    while (true)
                    {
                        Thread.Sleep(100);
                        if (status1 == 4)
                        {
                            break;
                        }
                    }
                    Thread.Sleep(3000);
                    //Send("{\"gMac\":\"d81105000101\", \"msgid\":1, \"opt\":4, \"mac\":[\"dff48f18f5bc\"]}");
                    Send("{\"gMac\":\"d81105000101\", \"msgid\":1, \"opt\":4, \"mac\":[\"b001000021d9\"]}");
                }
                //Send(textBoxMsg.Text.Trim());
            });
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string StrKey = this.comboBoxIps.SelectedItem.ToString();
            Socket socketNow = socketList.FirstOrDefault(p => p.Key == StrKey).Value;
            socketSend = socketNow;
        }
    }
}
